package jiangzuomanage.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/*
 * 数据库连接工具
 */
public class DbUtil {

    static String ip = "192.168.99.100";
    static int port = 3306;
    static String database = "jiangzuo";      //此处可灵活修改
    static String encoding = "UTF-8";
    static String loginName = "root";      //此处可灵活修改
    static String password = "ecai";      //此处可灵活修改
    static {
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    } 
    
    public static Connection getConnection()  {
        String url = String.format("jdbc:mysql://%s:%d/%s?characterEncoding=%s", ip, port, database, encoding);
        try {
            return DriverManager.getConnection(url, loginName, password);
        } catch (SQLException e) {
            e.printStackTrace();
            return getConnection();
        }
    }
    //测试用例
    public static void main(String[] args) throws SQLException {
        System.out.println(getConnection());
        
    }

    public static void close(Connection connection , PreparedStatement ps){
        if(connection != null){
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if(ps != null){
            try {
                ps.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}